package com.gjintel.business.webcontent.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpSession;

import com.gjintel.auction.business.model.AuctionInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gjintel.business.proj.model.ProjectInfo;
import com.gjintel.business.proj.service.impl.NotifyServiceImpl;
import com.gjintel.business.webcontent.dto.Combo;
import com.gjintel.business.webcontent.model.WebContent;
import com.gjintel.business.webcontent.service.IWebContentService;
import com.gjintel.business.webtypemanage.model.WebTypeInfo;
import com.gjintel.business.webtypemanage.service.IWebTypeManageService;
import com.gjintel.framework.constant.ActivitiMap;
import com.gjintel.framework.constant.Constant;
import com.gjintel.framework.dataset.model.DataSet;
import com.gjintel.framework.dept.model.Dept;
import com.gjintel.framework.holidayset.service.IHolidaySetService;
import com.gjintel.framework.log.model.LogInfo;
import com.gjintel.framework.log.model.TSysWarningLog;
import com.gjintel.framework.log.util.LogUtil;
import com.gjintel.framework.log.util.LogUtil.LogType;
import com.gjintel.framework.register.model.RegisterUser;
import com.gjintel.framework.register.service.IRegisterUserService;
import com.gjintel.framework.res.model.Resources;
import com.gjintel.framework.role.model.Role;
import com.gjintel.framework.user.model.User;
import com.gjintel.framework.util.CommUtil;
import com.gjintel.framework.util.FileResUtil;
import com.gjintel.sdk.base.dao.Page;
import com.gjintel.sdk.base.dao.Sort;
import com.gjintel.sdk.util.DateUtils;
import com.gjintel.sdk.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@RequestMapping("/business/webcontent")
@Controller
public class WebContentController {
	@Autowired
	private IWebContentService webContentService;

	@Autowired
	private IWebTypeManageService webManageService;

	@Autowired
	private IRegisterUserService registerUserService;

	@Autowired
	private IHolidaySetService holidaySetServiceImpl;

	@Autowired
	private NotifyServiceImpl notifyService;

	/** 质疑 */
	private final static String QUESTION = "21";
	/** 投诉 */
	private final static String COMPLAINTS = "22";
	/** 答疑 */
	private final static String REPLY = "23";
	/** 处理结果 */
	private final static String HANDLE = "24";

	/**
	 * @description 根据ID对角色信息进行添加、修改操作
	 * @author Ant-K
	 * @date 2016-03-19 下午04:40:09
	 * @param id
	 * @return
	 * @return ModelAndView
	 */
	@RequestMapping("/input")
	public ModelAndView input(String id) {
		ModelAndView mv = new ModelAndView("/business/webcontent/web-content-input");
		if (!StringUtil.isEmpty(id)) {
			WebContent webcontent = webContentService.findAll(id).get(0);
			// List<ArticManage> typelist=webManageService.findAll();
			mv.addObject("webcontent", webcontent);
			// mv.addObject("artcletype", typelist);
		}
		return mv;
	}

	/**
	 * @description 新建图片文件夹
	 * @author Ant-K
	 * @date 2016-3-20 上午09:23:05
	 * @param session
	 * @param info
	 * @return
	 * @return String
	 * @throws Exception
	 */
	@RequestMapping("/save")
	@ResponseBody
	public String save(HttpSession session, WebContent info, String budgetMenuData, String projectId) throws Exception {
		User user = (User) session.getAttribute("loginUser");
		if (info != null) {
			if (StringUtil.isEmpty(info.getId())) {
				info.setId(null);
				info.setCreateTime(new Date());
				info.setCreaterName(user.getName());
				info.setCreaterId(user.getId());
			}
			List<Dept> list = webManageService.getDeptName(user.getDeptId());
			info.setDeptName(list.get(0).getName());
			info.setDeptId(user.getDeptId());
			info.setUpdateTime(new Date());
			info.setUpdaterName(user.getName());
			info.setUpdaterId(user.getId());
			info.setProjectId(projectId);// 项目Id
			// 被曝光人信息
			if (info.getExploreUserId() != null && !info.getExploreUserId().equals("")) {
				RegisterUser register = this.registerUserService.getRegisterById(info.getExploreUserId());
				info.setExploreUserName(register.getLoginName());
			}
			this.webContentService.saveOrUpdate(info);
			String resStr = "<br><strong>附件：</strong>";
			// 保存关联附件信息
			if (budgetMenuData != null) {
				String budgetMenuStr[] = budgetMenuData.split(",");
				Resources res = null;
				for (String budgetMenuId : budgetMenuStr) {
					res = FileResUtil.getResources(budgetMenuId);
					if (res != null) {
						res.setBusinessId(info.getId());
						this.webContentService.saveOrUpdate(res);// 更新
						resStr += "<a href='../web/fileView?resId=" + res.getId() + "'>" + res.getOldName() + "</a> ";
					}
				}
			}
			if (budgetMenuData != null) {
				info.setContent(info.getContent() + resStr);// 将附件加入内容中
			}
			// 判断是否为变更公告操作
			if ("34".equals(info.getType())) {// 变更公告
//				System.err.println("---------------->变更公告");
//				DataSet dataset = this.webContentService.get(DataSet.class, Constant.DATASET_ID);
//				// Date changeEndTime = new SimpleDateFormat("yyyy-MM-dd
//				// HH:smm:ss")//
//				// .parse(StringUtil.computeDate(info.getCreateTime(),
//				// "00:00:00", dataset.getChangePublicity()+1));
//				Date changeEndTime = new SimpleDateFormat("yyyy-MM-dd HH:smm:ss")//
//						.parse(DateUtils.computeWorkDayDateStr(holidaySetServiceImpl, info.getCreateTime(),
//								dataset.getChangePublicity()));// (工作日));
//				info.setEndShowTime(changeEndTime);

				// 发送消息至信息管理员
//				AuctionInfo project = this.webContentService.get(AuctionInfo.class, projectId);
//				TSysWarningLog message = new TSysWarningLog();
//				message.setTitle("系统信息");
//				message.setContents(project.getAuctionName() + "变更公告已发布，请查看!");
//				List<Role> roles = new ArrayList<>();
				// 信息管理员
//				Role messager = this.webContentService.get(Role.class, ActivitiMap.MESSAGER_ID);
//				roles.add(messager);
//				notifyService.saveMessageByRoles(message, roles);
			}

			// 根据发布内容增加消息
			//pushMessageBuType(info.getType(), projectId);

			LogUtil.addLog(new LogInfo("添加文章数据", user.getId(), user.getName(), String.valueOf(LogType.ADD.ordinal()),
					info.getClass().getSimpleName(), info.getId()));
			return Constant.SAVE_SUCCESS;
		}
		return Constant.SAVE_UN_SUCCESS;
	}

	/**
	 * 根据发布内容增加消息
	 *
	 * @param type
	 */
	private void pushMessageBuType(String type, String projectId) {
		AuctionInfo project = this.webContentService.get(AuctionInfo.class, projectId);
		switch (type) {
		case QUESTION:
			// 发送消息至信息管理员
			TSysWarningLog message = new TSysWarningLog();
			message.setTitle("系统信息");
			message.setContents(project.getAuctionName() + "质疑已发布，请查看!");
			List<Role> roles = new ArrayList<>();
			// 信息管理员
//			Role messager = this.webContentService.get(Role.class, ActivitiMap.MESSAGER_ID);
//			roles.add(messager);
			notifyService.saveMessageByRoles(message, roles);
			break;
		case COMPLAINTS:
			// 发送消息至信息管理员
			message = new TSysWarningLog();
			message.setTitle("系统信息");
			message.setContents(project.getAuctionName() + "投诉已发布，请查看!");
			roles = new ArrayList<>();
			// 信息管理员
//			messager = this.webContentService.get(Role.class, ActivitiMap.MESSAGER_ID);
//			roles.add(messager);
			notifyService.saveMessageByRoles(message, roles);
			break;
		case REPLY:
			// 发送消息至信息管理员
			message = new TSysWarningLog();
			message.setTitle("系统信息");
			message.setContents(project.getAuctionName() + "答疑已发布，请查看!");
			roles = new ArrayList<>();
			// 信息管理员
//			messager = this.webContentService.get(Role.class, ActivitiMap.MESSAGER_ID);
//			roles.add(messager);
			notifyService.saveMessageByRoles(message, roles);
			break;
		case HANDLE:
			// 发送消息至信息管理员
			message = new TSysWarningLog();
			message.setTitle("系统信息");
			message.setContents(project.getAuctionName() + "处理结果已发布，请查看!");
			roles = new ArrayList<>();
			// 信息管理员
//			messager = this.webContentService.get(Role.class, ActivitiMap.MESSAGER_ID);
//			roles.add(messager);
			notifyService.saveMessageByRoles(message, roles);
			break;
		default:
			break;
		}
	}

	/**
	 * @description 分页查询数据
	 * @author Ant-K
	 * @date 2016-3-19 下午03:55:40
	 * @param page
	 * @param
	 * @param sort
	 * @return
	 * @return JSONObject
	 */
	@RequestMapping("/list")
	@SuppressWarnings("unchecked")
	@ResponseBody
	public JSONObject list(HttpSession session, Page page, WebContent webcontent, Sort sort, java.sql.Date startTime,
			java.sql.Date endTime, String deptId, Boolean noEditPubType) {
		User user = (User) session.getAttribute("loginUser");
		deptId = user.getDeptId();
		if (endTime != null) {
			Calendar c = Calendar.getInstance();
			c.setTime(endTime);
			c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) + 1);
			endTime = new java.sql.Date(c.getTime().getTime());
		}
		sort.setFields("createTime");
		sort.setOrders("desc");
		this.webContentService.findAll(page, webcontent, sort, startTime, endTime, deptId, noEditPubType);
		List<WebContent> list= page.getResult();
		for(WebContent web:list){
			if(web.getType().equals("32")){//中标公告
				web.setConfirmTime(web.getCreateTime());
			}
		}
		return CommUtil.getPageJSONData(page, true);
	}

	/**
	 * 查询质疑投诉信息列表
	 *
	 * @param session
	 * @param page
	 * @param webcontent
	 * @param sort
	 * @return
	 */
	@RequestMapping("/oppugnList")
	@SuppressWarnings("unchecked")
	@ResponseBody
	public JSONObject oppugnList(HttpSession session, Page page, WebContent webcontent, Sort sort) {
		User user = (User) session.getAttribute("loginUser");
		this.webContentService.findOppugnWebContentList(page, webcontent);
		return CommUtil.getPageJSONData(page, true);
	}

	/**
	 * @description 得的所有的记录数据
	 * @author Ant-K
	 * @date 2016-3-15 下午03:55:22
	 * @return
	 * @return JSONArray
	 */
	@RequestMapping("/typeList")
	@ResponseBody
	public JSONArray typeList() {
		List<WebTypeInfo> list = this.webManageService.findAll();
		Iterator<WebTypeInfo> TypeIt = list.iterator();
		List<WebTypeInfo> typeList = new ArrayList<WebTypeInfo>();
		// System.out.println(Constant.QUERY+"-----------------------------------");
		WebTypeInfo temp = null;
		// 移除父节点
		while (TypeIt.hasNext()) {
			temp = TypeIt.next();
			if (temp.getPid() != null && !temp.getName().equals(Constant.QUERY)
					&& !temp.getName().equals(Constant.RESULT) && !temp.getName().equals(Constant.ANSWER)
					&& !temp.getName().equals(Constant.COMPLAIN) && temp.getIsDisplay() == 1) {
				typeList.add(temp);
			}
		}
		return JSONArray.fromObject(typeList);
	}

	/**
	 * @description 得的所有的记录数据(查询)
	 * @author Ant-K
	 * @date 2016-3-15 下午03:55:22
	 * @return
	 * @return JSONArray
	 */
	@RequestMapping("/typeListFromSearch")
	@ResponseBody
	public JSONArray typeListFromSearch() {
		List<WebTypeInfo> list = this.webManageService.findAll();
		Iterator<WebTypeInfo> TypeIt = list.iterator();
		List<WebTypeInfo> typeList = new ArrayList<WebTypeInfo>();
		// System.out.println(Constant.QUERY+"-----------------------------------");
		WebTypeInfo temp = null;
		// 移除父节点
		while (TypeIt.hasNext()) {
			temp = TypeIt.next();
			if (temp.getPid() != null&&!"1".equals(temp.getPid() ) ) {//1 为文章类型
				//质疑投诉
//				&& !temp.getName().equals(Constant.QUERY)
//				&& !temp.getName().equals(Constant.RESULT) && !temp.getName().equals(Constant.ANSWER)
//				&& !temp.getName().equals(Constant.COMPLAIN)
				typeList.add(temp);
			}
		}
		return JSONArray.fromObject(typeList);
	}

	/**
	 * @description 删除数据
	 * @author Ant-K
	 * @date 2016-3-19 下午03:56:08
	 * @param deleteIds
	 * @return
	 * @throws Exception
	 * @return String
	 */
	@RequestMapping("/remove")
	@ResponseBody
	public String remove(HttpSession session, String deleteIds) throws Exception {
		this.webContentService.removeData(deleteIds);
		User user = (User) session.getAttribute("loginUser");
		LogUtil.addLog(new LogInfo("删除商品类型数据", user.getId(), user.getName(), String.valueOf(LogType.DELETE.ordinal()),
				WebContent.class.getSimpleName(), deleteIds));
		// InitCacheData.getInstance().initGoodsTypeData();
		return Constant.DEL_SUCCESS;
	}

	/**
	 * @description 获取 质疑投诉类别
	 * @author wwang
	 * @date 2016年9月18日
	 * @return
	 */
	@RequestMapping("/oppugnTypeList")
	@ResponseBody
	public JSONArray oppugnTypeList() {
		List<WebTypeInfo> list = this.webManageService.findAll();
		Iterator<WebTypeInfo> TypeIt = list.iterator();
		List<WebTypeInfo> typeList = new ArrayList<WebTypeInfo>();
		WebTypeInfo temp = null;
		// 移除父节点

		while (TypeIt.hasNext()) {
			temp = TypeIt.next();
			if (temp.getPid() != null && "2".equals(temp.getPid())) {// 2：质疑投诉
				typeList.add(temp);
			}
		}
		return JSONArray.fromObject(typeList);
	}

	/**
	 * 搜索自动完成
	 *
	 * @return
	 */
	@RequestMapping("/comboList")
	@ResponseBody
	public JSONArray comboList() {
		List<RegisterUser> registerList = this.webContentService.findAllComboList();
		List<Combo> comboList = new ArrayList<>();
		for (RegisterUser register : registerList) {
			Combo combo = new Combo();
			combo.setId(register.getId());
			combo.setText(register.getLoginName());
			combo.setSpell(register.getLoginName());
			comboList.add(combo);
		}
		return JSONArray.fromObject(comboList);
	}
}
